import { getSetting } from '@/services';
import { Effect, ImmerReducer, Reducer, addLocale, getAllLocales } from 'umi';

// 定义模块内部状态的类型
export interface SettingModelState {
  i18n: string;
  systemUrl: string;
  adminSystemUrl: string;
  systemTitle?: any;
  systemLogo: string;
  systemFavicon?: any;
  systemFooterInfo?: any;
  seoKeyword: string;
  seoDesc: string;
  baiduAnalyticsId: string;
  googleAnalyticsId: string;
}

// 定义模块的类型
export interface SettingModelType {
  namespace: 'setting';
  state: SettingModelState;
  effects: {
    getSetting: Effect;
  };
  reducers: {
    save: Reducer<SettingModelState>;
  };
}

const SettingModel: SettingModelType = {
  // 模块命名空间
  namespace: 'setting',

  // 模块内部状态
  state: {
    i18n: '',
    systemUrl: '',
    adminSystemUrl: '',
    systemTitle: '',
    systemLogo: '',
    systemFavicon: '',
    systemFooterInfo: '',
    seoKeyword: '',
    seoDesc: '',
    baiduAnalyticsId: '',
    googleAnalyticsId: '',
  },

  // 副作用
  effects: {
    *getSetting({ payload }, { call, put }) {
      const result = yield call(getSetting);
      if (result.statusCode === 200) {
        // 处理国际化的配置
        let i18n = JSON.parse(result.data.i18n);
        for (let key in i18n){
          addLocale(key, i18n[key], {
            momentLocale: key,
            antd: key,
          },);
        }
        // console.log(getAllLocales());
        yield put({
          type: 'save',
          payload: result.data
        })
      }
    }
  },

  // 同步修改
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    }
  }
};

export default SettingModel;